package com.leetcode.array;

import java.util.HashMap;
import java.util.Map;

public class MinWindow {
    public String minWindow(String s, String t) {
        Map<Character, Integer> need = new HashMap<>();
        Map<Character, Integer> window = new HashMap<>();
        for (char ch : t.toCharArray()) {
            need.put(ch, need.getOrDefault(ch, 0) + 1);
        }
        // [left, right)
        int left = 0;
        int right = 0;
        int len = Integer.MAX_VALUE;
        int start = 0;
        int count = 0;

        while (right < s.length()) {
            char curChar = s.charAt(right);
            right++;

            if (need.containsKey(curChar)) {
                window.put(curChar, window.getOrDefault(curChar, 0) + 1);
                if (need.get(curChar).intValue() == window.get(curChar).intValue()) {
                    count++;
                }
            }

            while (count == need.size()) {
                if (right - left < len) {
                    start = left;
                    len = right - left;
                }
                char leftChar = s.charAt(left);
                left++;

                if (need.containsKey(leftChar)) {
                    if (need.get(leftChar).intValue() == window.get(leftChar).intValue()) {
                        count--;
                    }
                    window.put(leftChar, window.getOrDefault(leftChar, 0) - 1);
                }
            }
        }
        return len == Integer.MAX_VALUE ? "" : s.substring(start, start + len);
    }

}
